<template>
  <div ref="chartRef" class="e-chart"></div>
</template>

<script lang="ts">
import * as echarts from 'echarts';
import { onMounted, ref, defineComponent, watch, onBeforeMount } from 'vue';
import { useDebounceFn } from '@vueuse/core';
import useThemeStore from '@/store/theme';
export default defineComponent({
  name: 'BizChart',
  components: {},
  provide: {},
  props: {
    options: {
      type: Object,
      default() {
        return null;
      },
    },
  },
  setup(props, context) {
    const theme = useThemeStore();
    const { themeColor } = theme.$state;
    const chartRef = ref<HTMLElement>();
    let myChart = null as any;
    const debouncedFn = useDebounceFn(() => {
      myChart.resize();
    }, 300);
    onMounted(() => {
      //基于准备好的dom，初始化echarts实例
      myChart = echarts.init(chartRef.value!);
      myChart.showLoading({
        text: '加载中',
        maskColor: 'rgba(0,0,0,0.1)',
        textColor: themeColor,
        color: themeColor,
      });
      myChart.on('finished', function () {
        context.emit('onload', myChart);
      });
      myChart.on('click', function (params: unknown) {
        context.emit('click', params);
      });
      window.addEventListener('resize', debouncedFn);
    });
    onBeforeMount(() => {
      window.removeEventListener('resize', debouncedFn);
    });
    watch(
      () => props.options,
      (newValue) => {
        //绘制图表
        myChart.setOption(newValue, { notMerge: true });
        myChart.hideLoading();
      },
      { deep: true }
    );
    return { chartRef };
  },
  data() {
    return {};
  },
});
</script>

<style scoped>
.e-chart {
  width: 100%;
  height: 100%;
}
</style>
